package com.yupi.springbootinit.service.impl;

import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.ai.AiResponse;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class AiManager {

    @Resource
    private ClientV4 clientV4;

    // ai 客户端
    //private static final ClientV4 client =
    // 业务id
    //TODO 待优化： 测试花费13s 是否改为流式调用
    //todo 生成不稳定 失败概率高
    private static final String requestIdTemplate = "mycompany" + RandomStringUtils.randomAlphanumeric(5);

    public AiResponse AiChart(String content) {
        AiResponse aiResponse = new AiResponse();
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(),
                content);
        messages.add(chatMessage);
        String requestId = String.format(requestIdTemplate, System.currentTimeMillis());
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                // 是否流式调用
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .requestId(requestId)
                .build();
        ModelApiResponse invokeModelApiResp = clientV4.invokeModelApi(chatCompletionRequest);
        aiResponse.setChartId(invokeModelApiResp.getData().getId());
        aiResponse.setSuccess(invokeModelApiResp.isSuccess());
        String chartResult = invokeModelApiResp.getData().getChoices().get(0).getMessage().getContent().toString();
        String[] parts = chartResult.split("【【【\nresult: ");
        if(parts.length < 2 || parts[0] == null || parts[1] ==null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"AI生成失败！！！");
        }
        String conclusionPart = parts[1].trim();
        String optionPart = parts[0].replace("option: ", "");
        optionPart = optionPart.replace("[\\n]", "");
        aiResponse.setChartConclusion(conclusionPart);
        aiResponse.setChartOption(optionPart);
        return aiResponse;
    }
}
